//画布

//存储画布相关信息
const Canvas = {
  canvas: null,
  ctx: null,
  position: {
    rx: 0,
    ry: 0,
    imageX: 0,
    imageY: 0,
    imageW: 0,
    imageH: 0
  }, //位置
  playImage: null, //播放
  pauseImage: null, //暂停
  dpr: 1,
}

function init(dpr) {
  Canvas.dpr = dpr
  wx.createSelectorQuery()
    .select('#song-progress')
    .fields({
      id: true,
      node: true,
      size: true
    })
    .exec(initProgress.bind(this))
}


//初始化画布
function initProgress(res) {
  const canvas = res[0].node
  const ctx = canvas.getContext('2d')
  const dpr = Canvas.dpr
  canvas.width = canvas._width * dpr
  canvas.height = canvas._height * dpr
  ctx.lineCap = "round";
  ctx.scale(dpr, dpr)

  const rx = canvas.width / 2
  const ry = canvas.height / 2

  Canvas.position = {
    rx: rx / 2,
    ry: ry / 2,
    imageX: 0,
    imageY: 0,
    imageW: rx,
    imageH: ry
  }

  Canvas.canvas = canvas
  Canvas.ctx = ctx

  drawCanvas(0, 0)
}

function drawCanvas(status, progress) {
  //画布清空
  const ctx = Canvas.ctx
  ctx.clearRect(0, 0, Canvas.canvas.width, Canvas.canvas.height)
  drawImage(status)
  drawBg()
  drawProgress(progress)
}

//绘制背景
function drawBg() {
  const ctx = Canvas.ctx
  const rx = Canvas.position.rx
  const ry = Canvas.position.ry
  ctx.beginPath()
  ctx.strokeStyle = '#ccc'
  ctx.arc(rx, ry, rx - 4, 0, Math.PI * 2, false)
  ctx.fillStyle = 'transparent'
  ctx.fill()
  ctx.stroke()
}
//绘制图片
function drawImage(status) {
  // const status = this.data.currentMusic.status //0 当前暂停 1 当前播放
  const src = status == 0 ? './../../image/icon_play.png' : './../../image/icon_pause.png'
  if (status == 0 && Canvas.playImage != null) {
    //播放按钮
    Canvas.ctx.drawImage(Canvas.playImage, Canvas.position.imageX, Canvas.position.imageY, Canvas.position.imageW, Canvas.position.imageH)

  } else if (status == 1 && Canvas.pauseImage != null) {
    //暂停按钮
    Canvas.ctx.drawImage(Canvas.pauseImage, Canvas.position.imageX, Canvas.position.imageY, Canvas.position.imageW, Canvas.position.imageH)
  } else {
    const image = Canvas.canvas.createImage()

    image.onload = () => {
      const dx = Canvas.position.imageX
      const dy = Canvas.position.imageY

      if (status == 0) {
        Canvas.playImage = image
      } else {
        Canvas.pauseImage = image
      }
      Canvas.ctx.drawImage(image, dx, dy, Canvas.position.imageW, Canvas.position.imageH)
    }

    image.src = src
  }

}
//绘制进度
function drawProgress(progress) {
  if (progress == 0) return
  const ctx = Canvas.ctx
  const rx = Canvas.position.rx
  const ry = Canvas.position.ry
  ctx.beginPath()
  ctx.strokeStyle = '#000'
  const angle = Math.PI * 2 * progress - Math.PI / 2
  ctx.arc(rx, ry, rx - 4, -Math.PI / 2, angle, false)
  ctx.fillStyle = 'transparent'
  ctx.fill()
  ctx.stroke()
}

export {
  init,
  drawCanvas,
  drawProgress
}